<?php

declare (strict_types = 1);

namespace app\common\model\user;

use app\common\enum\CointsType;
use app\common\model\User;
use cores\BaseModel;
use think\model\relation\BelongsTo;

/**
 * 用户积分变动明细模型
 * Class PointsLog
 * @package app\common\model\user
 */
class CointsLog extends BaseModel
{
    // 定义表名
    protected $name = 'user_coins_log';

    // 定义主键
    protected $pk = 'log_id';

    protected $updateTime = false;

    /**
     * 关联会员记录表
     * @return \think\model\relation\BelongsTo
     */
    public function user():BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\User");
    }


    /**日志写入
     * @param $scene
     * @param $user_id
     * @param $coins
     * @param string $remark
     * @return bool
     */
    public static function write($scene, $user_id, $coins, string $remark = ''):bool
    {
        //刷新redis
        $res = (new User())->syncRedis($user_id);
        if(!$res){
            throwError('flush redis data error');
        }
        //记录之前和之后的金币
        $user_info = (new User())->where('user_id',$user_id)->find();
        if($coins >= 0){
            $before_value = $user_info->coins - $coins >= 0 ?  ($user_info->coins - $coins) : 0;
        }else{
            $before_value = $user_info->coins + abs($coins);
        }
        $after_value = $user_info->coins;
        return (new static())->save([
            'scene' => $scene,
            'user_id' => $user_id,
            'value' => $coins,
            'describe' => CointsType::data()[$scene]['name'],
            'remark' => $remark,
            'before_value' => $before_value,
            'after_value' => $after_value
        ]);
    }

}
